package com.example.demo.controller;

import com.example.demo.model.FileBean;
import com.example.demo.model.Result;
import com.example.demo.model.UserBean;
import com.example.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class FileUploadController {

    @Autowired
    FileService fileService;

    @GetMapping("login")
    public String login(Model model) {
        model.addAttribute("list",fileService.FindAll());
        return "homepage";
    }

    @RequestMapping(value = "/userLogin/submit", method = RequestMethod.POST)
    @ResponseBody
    public Result userLogin(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);
        HttpSession session = request.getSession();
        Result r = new Result();
        UserBean userBean = new UserBean();
        userBean.setUserName(username);
        userBean.setPassWord(password);
        if (!(username.equals("123") && password.equals("123"))) {
            r.setCode(300);
            r.setMessage("用户名不存在");
            return Result.error(userBean);
        } else {
            r.setCode(200);
            r.setMessage("登录成功");
            return Result.ok(userBean);
        }
    }

    //文件上传
    @RequestMapping(value = "/myloadfile")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile[] files) {
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                System.out.println("上传的文件为空！");
            }
            // 文件名
            String fileName = file.getOriginalFilename();
            // 获取文件后缀名
            String extension = fileName.substring(fileName.indexOf("."));
            String uuid=UUID.randomUUID().toString();
            fileName = uuid + extension;
            // 上传文件的路径
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date(System.currentTimeMillis());
            String uploadFolder = "E://upload_file/" + formatter.format(date) + "/";
            File dest = new File(uploadFolder + fileName);
            // 检测文件目录是否存在 不存在则创建
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                System.out.println("上传文件成功！");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("上传文件失败！");
            }
            // 返回虚拟文件访问路径
            FileBean fileBean = new FileBean(0, file.getSize() + "",
                    extension, fileName, formatter.format(date),uuid,
                    "http://127.0.0.1:8888/upload/" + formatter.format(date) + "/" + fileName);
            fileService.InsertFile(fileBean);
            return uuid;
        }

        // 返回虚拟文件访问路径
        return "http://127.0.0.1:8888/upload/";
    }

    // 所有类型文件下载管理
    @PostMapping("/godownload")
    public ResponseEntity<byte[]> fileDownload(HttpServletResponse resp,HttpServletRequest request,
                                               @RequestParam("search") String uuid) throws Exception {
        // 指定要下载的文件根路径
        String dirPath = "E:/upload_file/";
        FileBean fileBean = fileService.FindByUuid(uuid);
        if(fileBean==null) {
            String data = "410错误";
            OutputStream outputStream = resp.getOutputStream();// 获取输出流
            // 通过设置响应头控制浏览器以UTF-8的编码显示数据，如果不加这句话，那么浏览器显示的将是乱码
            resp.setHeader("content-type", "text/html;charset=UTF-8");
            resp.setStatus(410);
            // 将字符转换成字节数组，指定以UTF-8编码进行转换
            byte[] dataByteArr = data.getBytes("UTF-8");
            //使用OutputStream流向客户端输出字节数组
            outputStream.write(dataByteArr);
            outputStream.flush();
            outputStream.close();
        }
        dirPath+=fileBean.getTime()+"/";
        String filename = fileBean.getFilename();
        // 创建该文件对象
        File file = new File(dirPath+filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载方式打开（下载前对文件名进行转码）
        filename = getFilename(request, filename);
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED);
        }
    }
    // 所有类型文件下载管理
    @GetMapping("/godownload")
    public ResponseEntity<byte[]> godownload(HttpServletResponse resp, HttpServletRequest request, String uuid) throws Exception {
        // 指定要下载的文件根路径
        String dirPath = "E:/upload_file/";
        FileBean fileBean = fileService.FindByUuid(uuid);
        if(fileBean==null) {
            String data = "410错误";
            OutputStream outputStream = resp.getOutputStream();// 获取输出流
            // 通过设置响应头控制浏览器以UTF-8的编码显示数据，如果不加这句话，那么浏览器显示的将是乱码
            resp.setHeader("content-type", "text/html;charset=UTF-8");
            resp.setStatus(410);
            // 将字符转换成字节数组，指定以UTF-8编码进行转换
            byte[] dataByteArr = data.getBytes("UTF-8");
            //使用OutputStream流向客户端输出字节数组
            outputStream.write(dataByteArr);
            outputStream.flush();
            outputStream.close();
        }
        dirPath+=fileBean.getTime()+"/";
        String filename = fileBean.getFilename();
        // 创建该文件对象
        File file = new File(dirPath+filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载方式打开（下载前对文件名进行转码）
        filename = getFilename(request, filename);
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED);
        }
    }

    // 根据浏览器的不同进行编码设置，返回编码后的文件名
    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示，并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+", " ");
            }
        }
        //火狐等其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }

    //文件元信息获取
    @GetMapping(value = "/getfile")
    @ResponseBody
    public String fileUpload( String uuid) {
//        System.out.println(uuid+"-----------------------------");
        return fileService.FindByUuid(uuid).toString();
    }

}
